﻿<%@ WebHandler Language="C#" Class="HandlerImageManager" %>

using System;
using System.Web;
using System.Web.SessionState;
using Newtonsoft;
using BLL;
using System.IO;
using Config;
using Utils;
using System.Linq;
using System.Collections.Generic;

public class HandlerImageManager : IHttpHandler, IReadOnlySessionState
{

    public void ProcessRequest(HttpContext context)
    {
        string strAction = context.Request.QueryString["action"] ?? string.Empty;
        int typeImage =Convert.ToInt32(context.Request.QueryString["type"] ?? "-1");
        bool isGeneral = Convert.ToBoolean(context.Request.QueryString["isGeneral"] ?? "false");

        // Lấy danh sách ảnh
        if (strAction == "get")
        {
            var imageList = GetImages(typeImage, isGeneral);

            // Convert đối tượng sang chuỗi json
            string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(imageList);

            // Đẩy ra context
            context.Response.ContentType = "application/json";
            context.Response.Write(jsonString);
        }

        // Xóa ảnh
        else if (strAction == "del")
        {
            string strName = context.Request.QueryString["name"] ?? string.Empty;

            int result = DelImage(strName, typeImage, isGeneral);

            context.Response.ContentType = "application/json";
            context.Response.Write(result);

        }
        else if (strAction == "upload")
        {
            HttpPostedFile postFile = context.Request.Files["Filedata"];
            string name = context.Request.Params["txtImageName"] ?? string.Empty;
            name = Library.HtmlUtility.HtmlEncode(name.Trim().Replace(" ", "_"));
            int result = Upload(postFile, name, typeImage, isGeneral);
            context.Response.ContentType = "text/plain";
            if (result == 1)
            {
                string strExt = postFile.FileName.Substring(postFile.FileName.LastIndexOf(".")).ToLower();
                context.Response.Write(result + "|" + name + strExt);
            }
            else
            {
                context.Response.Write(result);
            }
        }
    }

    /// <summary>
    /// Upload ảnh
    /// </summary>
    /// <param name="postFile"></param>
    /// <param name="type"></param>
    /// <param name="strName"></param>
    /// <returns>1: Thành công, -1: Sai định dạnh cho phép, -2: Kích thước ảnh > 2MB</returns>
    private int Upload(HttpPostedFile postFile, string strName,int type, bool isGeneral)
    {
        string strExt = postFile.FileName.Substring(postFile.FileName.LastIndexOf(".")).ToLower();
        string strExts = ".jpg|.png|.gif";
        if (strExts.IndexOf(strExt) == -1)
        {
            return -1;
        }
        else if (postFile.ContentLength > 2097152)
            return -2;
        else   
        {
            string path = string.Empty;
            path = GetPath(type, isGeneral);
            if (Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = path + strName + strExt;
            postFile.SaveAs(fileName);
            return 1;
        }
    }


    /// <summary>
    /// Xóa ảnh
    /// </summary>
    /// <param name="strName"></param>
    /// <returns>1: Thành công, -1: Không tồn tại File, -2: Không tồn tại loại ảnh</returns>
    private int DelImage(string strName, int type,bool isGeneral)
    {

        string path = string.Empty;
        string strKeyCache = string.Empty;

        path = GetPath(type, isGeneral);

        path = path + strName;
        if (File.Exists(path))
        {
            File.Delete(path);
            return 1;
        }
        else
        {
            return -1;
        }
    }

    /// <summary>
    /// Lấy danh sách ảnh
    /// </summary>
    /// <returns></returns>
    private List<Entity.Image> GetImages(int type, bool isGeneral)
    {
        List<Entity.Image> listImage = new List<Entity.Image>();

        string path = string.Empty;
        string strKeyCache = string.Empty;
        string strURL = string.Empty;

        path = GetPath(type, isGeneral);
        strURL = GetServicePhoto(type, isGeneral);
        
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        var filePaths = Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)
        .Where(s => s.EndsWith(".gif") || s.EndsWith(".jpg") || s.EndsWith(".png"));
        int i = 1;
        foreach (var filePath in filePaths)
        {
            FileInfo fileInfo = new FileInfo(filePath);
            Entity.Image objImage = new Entity.Image();
            objImage.Name = fileInfo.Name;
            objImage.Size = (fileInfo.Length / 1024.0).ToString("0.0");
            objImage.URL = strURL + objImage.Name;
            objImage.Id = "img_" + i.ToString();
            listImage.Add(objImage);
            i++;
        }
        return listImage;
    }
    private string GetPath(int type, bool isGeneral)
    {
        string path = string.Empty;        
        switch (type)
        {
                
            case 1:
                if (isGeneral)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/general/product/");
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/hilo/product/");
                }
                else
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/test/product/");
                }
                break;
            case 2:
                if (isGeneral)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/general/news/");
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/hilo/news/");
                }
                else
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/test/news/");
                }
                break;
            case 3:
                if (isGeneral)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/general/help/");
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/hilo/help/");
                }
                else
                {
                    path = HttpContext.Current.Server.MapPath("~/resources/test/help/");
                }
                break;
        }
        return path;
    }
    private string GetServicePhoto(int type, bool isGeneral)
    {
        string strURL = string.Empty;

        switch (type)
        {
            case 1:
                if (isGeneral)
                {
                    strURL =  "/resources/general/product/";
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    strURL =  "/resources/hilo/product/";
                }
                else
                {
                    strURL = "/resources/test/product/";
                }
                break;
            case 2:
                if (isGeneral)
                {
                    strURL =  "/resources/general/news/";
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    strURL =  "/resources/hilo/news/";
                }
                else
                {
                    strURL = "/resources/test/news/";
                }
                break;
            case 3:
                if (isGeneral)
                {
                    strURL =  "/resources/general/help/";
                }
                else if (AdminUtils.ServicesID == 1)
                {
                    strURL = "/resources/hilo/help/";
                }
                else
                {
                    strURL = "/resources/test/help/";
                }
                break;
        }
        return strURL;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}